package com.xyzm.mytest.nio;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 一、使用NIO完成通信的三个核心
 *  1、通道（channel）：负责连接
 *      java.nio.channels.Channel接口
 *              |--SelectableChannel
 *                  |--SocketChannel
 *                  |--ServerSocketChannel
 *                  |--DatagramSocketChannel
 *
 *                  |--Pipe.SinkChannel
 *                  |--Pipe.SourceChannel
 *  2、缓冲区（buffer）：负责数据的存取
 *  3、选择器（selector）：是SelectableChannel的多路复用器，用于监控SelectableChannel的IO状况
 */
public class TestBlockingNIO {
    //客户端
    @Test
    public void client() throws IOException {
        FileChannel fileChannel = FileChannel.open(Paths.get("E:\\MyTest\\孙悟空.txt"), StandardOpenOption.READ);
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        //数据传输
        while (fileChannel.read(byteBuffer)!=-1){
            byteBuffer.flip();
            socketChannel.write(byteBuffer);
            byteBuffer.clear();
        }
        //数据传输完成
        socketChannel.shutdownOutput();
        //接收服务器返回数据
        int len = 0;
        while ((len = socketChannel.read(byteBuffer))!=-1){
            byteBuffer.flip();
            System.out.println(new String(byteBuffer.array(),0,len));
            byteBuffer.clear();
        }
        fileChannel.close();
        socketChannel.close();
    }

    //服务端
    @Test
    public void server() throws IOException {
        FileChannel fileChannel = FileChannel.open(Paths.get("E:\\MyTest\\孙悟空-receive.txt"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(9898));
        SocketChannel socketChannel = serverSocketChannel.accept();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        //接受客户端发送的数据
        while (socketChannel.read(byteBuffer)!=-1){
            byteBuffer.flip();
            fileChannel.write(byteBuffer);
            byteBuffer.clear();
        }
        //向客户端发送数据
        byteBuffer.put("服务器接受数据成功！".getBytes());
        byteBuffer.flip();  //读模式
        socketChannel.write(byteBuffer);
        fileChannel.close();
        socketChannel.close();
        serverSocketChannel.close();
    }
}
